/**
 * Created by 3dgis on 2017/4/4.
 */
import {applyMiddleware, createStore} from "redux";
import logger from "redux-logger";
import thunk from "redux-thunk";
import axios from "axios";

const initialState = {
    fetching:false,
    fetched:false,
    result:'',
    error:null
}

const reducer = (state=initialState,action)=>{
    switch (action.type){
        case "FETCH_SEARCH_RESULT":{
            return {...state,fetching:true}
            break;
        }
        case "RECEIVE_SEARCH_RESULT":{
            return {
                ...state,
                fetching:false,
                result:action.payload,
                fetched:true,
            }
            break;
        }
        case "FETCH_RESULT_ERROR":{
            return {...state,fetching:false,error:action.payload}
            break;
        }
    }
    return state;
}
const middleware = applyMiddleware(thunk,logger)
const store = createStore(reducer,middleware)

store.dispatch((dispatch)=>{
    dispatch({type:"FETCH_SEARCH_RESULT"})
    axios.get('http://map.tianditu.com/query.shtml?postStr={"keyWord":"天安门","level":"12","mapBound":"-180,-90,180,90","queryType":"1","start":"0","count":"10"}&type=query')
        .then((response)=>{
            dispatch({type:"RECEIVE_SEARCH_RESULT",payload:response.data})
        })
        .catch((err)=>{
            dispatch({type:"FETCH_RESULT_ERROR",payload:err})
        })
    //do something async
})

/*lesson 5 middleware
 const reducer = (initialState=0,action)=>{
 if(action.type==="INC"){
 return initialState+1;
 }
 else if(action.type==="DEC"){
 return initialState-1;
 }
 else if(action.type==="E"){
 throw new Error("你错了！")
 }
 return initialState;
 }

 //logger middleware
 const logger = (store) => (next) =>(action)=>{
 console.log("action fired", action);
 next(action);
 }
 //error middleware
 const error = (store)=>(next) => (action)=>{
 try{
 next(action);
 }catch(e){
 console.log("你错了！！");
 }
 }

 const middleware = applyMiddleware(logger,error);

 const store = createStore(reducer,1,middleware)

 store.subscribe(()=>{
 console.log("store changed", store.getState())
 })

 store.dispatch({type:"INC"})
 store.dispatch({type:"INC"})
 store.dispatch({type:"INC"})
 store.dispatch({type:"DEC"})
 store.dispatch({type:"DEC"})
 store.dispatch({type:"DEC"})
 store.dispatch({type:"E"})
 */
